#include "QtUI/DbProjectBrowserWidget.qth"
#include "QtUI/DbProjectBrowserWidget.moh"
#include "DbStorage/DbStorageFactory.hpp"
#include "CaseDB/Statement.hpp"
#include "CaseDB/RecordSet.hpp"
#include "CaseDB/Connection.hpp"
#include <QtGui/QHeaderView>
#include <boost/any.hpp>

Q_DECLARE_METATYPE( boost::any);

namespace QtUI
{

DbProjectBrowserWidget::DbProjectBrowserWidget( Storage::StorageFactory* storageFactory, QWidget* pParent/* = NULL*/)
	: QTableWidget( pParent)
	, pStorageFactory_( storageFactory)
{
	this->setColumnCount( 1);
	this->setEditTriggers( QAbstractItemView::NoEditTriggers);
	QStringList labels( tr("Project Name", "Column header for project name"));
	this->setHorizontalHeaderLabels( labels);
	this->horizontalHeader()->setResizeMode( QHeaderView::Stretch);

	this->populateList();
	this->setSelectionMode( QAbstractItemView::SingleSelection);
	this->setSelectionBehavior( QAbstractItemView::SelectRows);
}

// ---------------------------------------------------------------------------------------------------------------------

void DbProjectBrowserWidget::populateList()
{
	using namespace CaseDB;
	try
	{
		RecordSet::Metadata meta;
		meta.reserve( 3);
		meta.push_back( DbTypesEnum::Integer);	// ID
		meta.push_back( DbTypesEnum::String);	// Name
		meta.push_back( DbTypesEnum::String);	// Description
		RecordSet prjSet( meta);
		Statement dbStatement( "select PK_PROJECT, NAME, DESCRIPTION from PROJECTS order by NAME");
		dynamic_cast<DbStorage::DbStorageFactory*>( pStorageFactory_.get())->dbConnection().execute( dbStatement, prjSet);

		int index = 0;
		this->setRowCount( prjSet.numberOfRecords());
		RecordSet::ConstRecordIterator recI = prjSet.begin(),
			recEndI = prjSet.end();
		while( recI != recEndI)
		{
			QTableWidgetItem* pPrjItem = new QTableWidgetItem;
			std::string prjName = boost::any_cast< std::string>( (*recI)[1]);
			std::string prjDescr = boost::any_cast< std::string>( (*recI)[2]);
			pPrjItem->setText( QString::fromStdString( prjName));
			QVariant data;
			data.setValue( (*recI)[0]);
			pPrjItem->setData( Qt::UserRole, data);
			pPrjItem->setToolTip( QString::fromStdString( prjDescr));
			this->setItem( index, 0, pPrjItem);
			++recI;
			++index;
		}
	}
	catch( std::exception& e)
	{
		this->setRowCount( 1);
		QTableWidgetItem* pErrorItem = new QTableWidgetItem( e.what());
		this->setItem( 0, 0, pErrorItem);
	}
}

// ---------------------------------------------------------------------------------------------------------------------

boost::any DbProjectBrowserWidget::selectedProjectID() const
{
	int curIndex = this->currentRow();
	if( curIndex < 0)
	{
		return boost::any();
	}

	QVariant data = this->item( curIndex, 0)->data( Qt::UserRole);
	boost::any result = data.value< boost::any>();
	return result;
}

} // namespace QtUI
